import axios from "axios"; // 引入axios
import NProgress from "nprogress";
import { Notify } from "vant";
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "../Uitils/auth"; // getToken from cookie

export const serverUrl = "http://localhost:1337"; //服务器地址

export const instance = axios.create({
  baseURL: serverUrl, // 基础路径
  timeout: 5000, // 请求超时时间
});

// get请求
//1.参数1：请求地址
//2.参数2：请求参数
//3.参数3：请求成功的回调函数
export const get = (url, params) => {
  return instance.get(url, { params });
};
// export const get =(url,params)=> instance.get(url,{params})

// post请求
//1.参数1：请求地址
//2.参数2：请求参数
//3.参数3：请求成功的回调函数
export const post = (url, params) => {
  return instance.post(url, params);
};
// export const post =(url,params)=> instance.post(url,params)

//put请求
//1.参数1：请求地址
//2.参数2：请求参数
//3.参数3：请求成功的回调函数
export const put = (url, params) => {
  return instance.put(url, params);
};
// export const put =(url,params)=> instance.put(url,params)

//delete请求   删除
//1.参数1：请求地址
//2.参数2：请求参数
//3.参数3：请求成功的回调函数
export const deleteRequest = (url, params) => {
  return instance.delete(url, { params });
};
// export const del =(url,params)=> instance.delete(url,{params})

// 请求拦截器
// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start();
    config.headers.token = getToken();
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

//
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    NProgress.done();
    return response.data;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error

    if (error.response?.data) {
      Notify({
        message:
          error.response.status +
          "|" +
          (error.response.data.message
            ? error.response.data.message
            : error.response.data.info),
        type: "danger",
      });
    }
    NProgress.done();
    return Promise.reject(error);
  }
);
